/**
 * 试剂架列表页面
 */

import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Space,
  Divider,
  message,
  Table,
  Popconfirm,
  Typography,
  Select,
  Popover,
  Tooltip,
} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import ShelfPlane from "./ShelfPlane";
import MmPixBox from "../components/MmPixBox";
import { ITStore } from "../../store";
import {
  ITDictValue,
  ITColumns,
  ITShelf,
  ITBottle,
} from "../../store/interfaces";
type TProp = {
  store: ITStore;
};

type TBottleOpt = {
  label: string;
  value?: string;
};



const { Option } = Select;
const { Text, Link } = Typography;
const layout = {
  labelCol: { span: 12 },
  wrapperCol: { span: 12 },
};

const inputwide = {
  width: "100%",
};

// 搜索和新增按钮组件
const SearchAddComp: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang },
      shelfStore: { changeShowAddEditShelfModal },
    } = store;

    const handleClickAdd = () => {
      changeShowAddEditShelfModal(true);
    };

    return (
      <Row style={{ marginBottom: 20 }}>
        <Col span={12}></Col>
        <Col span={12}>
          <Space wrap style={{ float: "right" }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleClickAdd}
            >
              {lang["langbuttonadd"]}
            </Button>
          </Space>
        </Col>
      </Row>
    );
  })
);

// 新增 编辑试剂瓶弹窗
const AddEditShelfModal: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      shelfStore: {
        showAddEditShelfModal,
        changeShowAddEditShelfModal,
        editShelfData,
        currentShelfPlane,
        changeCurrentShelfPlane,
        addShelf,
        updateShelf,
        addShelfLoading,
        getAllShelf,
        changeEditShelfData,
        clearCurrentShelfPlane,
      },
      dictionaryStore: { getDictValuesByKey },
      bottleStore: { allBottle },
    } = store;

    const [form] = Form.useForm();

    const [bottleOption, setBottleOption] = useState<TBottleOpt[]>([]);

    const [rackOption, setRackOption] = useState<ITDictValue[]>([]);

    // 瓶子列表信息
    const [bottleListInfo, setBottleListInfo] = useState<any>(null);

    useEffect(() => {
      setRackOption(getDictValuesByKey("reagentRackType"));
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
      if (editShelfData) {
        form.setFieldsValue(editShelfData);
      }
    }, [editShelfData, form]);

    useEffect(() => {
      if (allBottle && allBottle.length) {
        let templist: TBottleOpt[] = [];
        allBottle.forEach(({ name, id }) => {
          templist.push({
            label: name,
            value: id,
          });
        });
        setBottleOption(templist);
      }
    }, [allBottle]);

    const close = () => {
      form.resetFields();
      changeEditShelfData(null);
      clearCurrentShelfPlane();
      changeShowAddEditShelfModal(false);
    };

    const bottleTypeChange = (data: any) => {
      // 获取瓶子直径和瓶子类型
      let bottleInfo: any = {};
      allBottle.some((item) => {
        if (item.id === data) {
          bottleInfo = item;
          return true;
        }
        return false;
      });
      changeCurrentShelfPlane({
        diameter: bottleInfo.diameter,
        bottleShape: bottleInfo.shape,
      });
    };

    const lengthChange = (data: any) => {
      changeCurrentShelfPlane({
        length: data,
      });
    };

    const wideChange = (data: any) => {
      changeCurrentShelfPlane({
        wide: data,
      });
    };

    const rowChange = (data: any) => {
      changeCurrentShelfPlane({
        row: data,
      });
    };

    const columnChange = (data: any) => {
      changeCurrentShelfPlane({
        column: data,
      });
    };

    const rowSpaceChange = (data: any) => {
      changeCurrentShelfPlane({
        rowSpace: data,
      });
    };

    const columnSpaceChange = (data: any) => {
      changeCurrentShelfPlane({
        columnSpace: data,
      });
    };

    const offsetXChange = (data: any) => {
      changeCurrentShelfPlane({
        offsetx: data,
      });
    };

    const offsetYChange = (data: any) => {
      changeCurrentShelfPlane({
        offsety: data,
      });
    };

    const formFinish = async (values: ITShelf) => {
      let result = null;
      let msg: string = "";
      const { name } = values;
      if (editShelfData) {
        const { bottleList } = currentShelfPlane;
        // 编辑
        result = await updateShelf({ ...values, name: name.trim(), bottleList });
        msg = lang["langmodifysuccess"];
      } else {
        // 新增
        const { id, ...addparam } = values;
        result = await addShelf({ ...addparam, bottleList: bottleListInfo });
        msg = lang["langaddsuccess"];
      }
      if (!result) {
        close();
        message.success(msg);
        getAllShelf();
      } else {
        const { msg } = result;
        message.error(msg);
      }
    };

    return (
      <Modal
        title={
          <Row>
            <Col span={12}>
              {!!editShelfData ? lang["langeditshelf"] : lang["langaddshelf"]}
            </Col>
            <Col span={11}>
              <Space style={{ float: "right" }}>
                <MmPixBox />
              </Space>
            </Col>
            <Col span={1}></Col>
          </Row>
        }
        open={showAddEditShelfModal}
        destroyOnClose={true}
        onOk={() => {
          form.submit();
        }}
        width="90%"
        confirmLoading={addShelfLoading}
        onCancel={close}
      >
        <Form {...layout} form={form} name="tubeRackForm" onFinish={formFinish}>
          <Form.Item name="id" label="" hidden={true}>
            <Input />
          </Form.Item>
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item
                name="name"
                label={lang["langname"]}
                rules={[{ required: true }]}
              >
                <Input style={inputwide} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="bottleType"
                label={lang["langbottletype"]}
                rules={[{ required: true }]}
              >
                <Select style={inputwide} onChange={bottleTypeChange}>
                  {bottleOption.map(({ label, value }, index) => (
                    <Option key={index} value={value}>
                      {label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="rackType"
                label={lang["langracktype"]}
                rules={[{ required: true }]}
              >
                <Select style={inputwide}>
                  {rackOption.map(({ cnlabel, label, value, sort }) => (
                    <Option key={sort} value={value}>
                      {langCur === "en" ? label : cnlabel}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="length"
                label={lang["langlength"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={lengthChange}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="wide"
                label={lang["langwide"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={wideChange}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="height"
                label={lang["langheight"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="row"
                label={lang["langrow"]}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={rowChange} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="column"
                label={lang["langcolumn"]}
                rules={[{ required: true }]}
              >
                <InputNumber style={inputwide} onChange={columnChange} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="rowSpace"
                label={lang["langrowspace"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={rowSpaceChange}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="columnSpace"
                label={lang["langcolumnspace"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={columnSpaceChange}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="offsetx"
                label={lang["langoffsetx"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={offsetXChange}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="offsety"
                label={lang["langoffsety"]}
                rules={[{ required: true }]}
              >
                <InputNumber
                  addonAfter={lang["langmmunit"]}
                  style={inputwide}
                  onChange={offsetYChange}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Divider />
        <ShelfPlane setBottleListInfo={setBottleListInfo} bottleListInfo={bottleListInfo} />
      </Modal>
    );
  })
);

const ShelfList: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      shelfStore: {
        allShelfLoading,
        getAllShelf,
        allShelf,
        delShelfLoading,
        delShelf,
        changeShowAddEditShelfModal,
        changeEditShelfData,
        changeCurrentShelfPlane,
      },
      bottleStore: { allBottle },
      dictionaryStore: { getDictValuesByKey },
    } = store;

    const [delData, setDelData] = useState<ITShelf | null>(null);

    const [rackOption, setRackOption] = useState<ITDictValue[]>([]);

    useEffect(() => {
      getAllShelf();
      setRackOption(getDictValuesByKey("reagentRackType"));
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const BottleContent = ({ data }: any) => {
      const bottleDict: ITDictValue[] = getDictValuesByKey("bottleshape");
      let bottleShape: any = null;
      bottleDict.some((item) => {
        if (item.value === data.shape) {
          bottleShape = item;
          return true;
        }
        return false;
      });
      return (
        <Space direction="vertical">
          <Text>
            {lang["langheight"]}: {data.height}{" "}
            <Text type="secondary">({lang["langmmunit"]})</Text>
          </Text>
          <Text>
            {lang["langdiameter"]}: {data.diameter}{" "}
            <Text type="secondary">({lang["langmmunit"]})</Text>
          </Text>
          <Text>
            {lang["langdepth"]}: {data.depth}{" "}
            <Text type="secondary">({lang["langmmunit"]})</Text>
          </Text>
          <Text>
            {lang["langvolume"]}: {data.volume}{" "}
            <Text type="secondary">({lang["langmlunit"]})</Text>
          </Text>
          {!!bottleShape && (
            <Text>
              {lang["langshape"]}:{" "}
              {langCur === "en" ? bottleShape.label : bottleShape.cnlabel}
            </Text>
          )}
        </Space>
      );
    };

    const deleteItem = async (record: ITShelf) => {
      setDelData(record);
      const { id } = record;
      const res = await delShelf({ id });
      if (!res) {
        getAllShelf();
        message.success(lang["langdeletesuccess"]);
        setDelData(null);
      }
    };

    const getBottleInfo = (
      bottles: ITBottle[],
      id: string
    ): ITBottle | null => {
      let bottle = null;
      bottles.forEach((item) => {
        if (item.id === id) {
          bottle = item;
          return true;
        }
        return false;
      });

      return bottle;
    };

    const modifyItem = async (record: ITShelf) => {
      changeEditShelfData(record);
      const { bottleType } = record;

      const bottleInfo = getBottleInfo(allBottle, bottleType);

      const {
        length,
        wide,
        row,
        column,
        rowSpace,
        offsety,
        offsetx,
        columnSpace,
        bottleList,
      } = record;

      if (bottleInfo) {
        changeCurrentShelfPlane({
          length,
          wide,
          row,
          column,
          rowSpace,
          columnSpace,
          bottleList,
          offsetx,
          offsety,
          diameter: bottleInfo.diameter,
          bottleShape: bottleInfo.shape,
        });
      }

      changeShowAddEditShelfModal(true);
    };

    const columns: ITColumns[] = [
      {
        title: lang["langname"],
        dataIndex: "name",
        key: "name",
      },
      {
        title: lang["langbottletype"],
        dataIndex: "bottleType",
        key: "bottleType",
        render: (txt: string) => {
          const bottleInfo = getBottleInfo(allBottle, txt);
          return (
            <Popover
              content={<BottleContent data={bottleInfo} />}
              title={bottleInfo?.name}
            >
              <Link>{bottleInfo?.name}</Link>
            </Popover>
          );
        },
      },
      {
        title: lang["langracktype"],
        dataIndex: "rackType",
        key: "rackType",
        render: (txt: string) => {
          let temp = ""
          rackOption.some(item => {
            if(item.value === txt){
              if(langCur === "en"){
                temp = item.label
              } else {
                temp = item.cnlabel;
              }
              return true;
            }
            return false;
          })
          return temp;
        },
      },
      {
        title: (
          <>
            <Text>{lang["langlength"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "length",
        key: "length",
      },
      {
        title: (
          <>
            <Text>{lang["langwide"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "wide",
        key: "wide",
      },
      {
        title: (
          <>
            <Text>{lang["langheight"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "height",
        key: "height",
      },
      {
        title: lang["langrow"],
        dataIndex: "row",
        key: "row",
      },
      {
        title: lang["langcolumn"],
        dataIndex: "column",
        key: "column",
      },
      {
        title: (
          <>
            <Text>{lang["langrowspace"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "rowSpace",
        key: "rowSpace",
      },
      {
        title: (
          <>
            <Text>{lang["langcolumnspace"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "columnSpace",
        key: "columnSpace",
      },
      {
        title: (
          <>
            <Text>{lang["langoffsetx"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "offsetx",
        key: "offsetx",
      },
      {
        title: (
          <>
            <Text>{lang["langoffsety"]}</Text>
            <Text type="secondary"> ({lang["langmmunit"]})</Text>
          </>
        ),
        dataIndex: "offsety",
        key: "offsety",
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        fixed: "right",
        render: (txt: string, record: ITShelf) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    loading={delData?.id === record.id && delShelfLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Table
        dataSource={allShelf}
        columns={columns}
        bordered
        loading={allShelfLoading}
      />
    );
  })
);

const Shelf: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    bottleStore: { getAllBottle },
  } = store;

  useEffect(() => {
    getAllBottle();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <>
      {/* 搜索和新增按钮组件 */}
      <SearchAddComp />

      {/* 试管架列表 */}
      <ShelfList />

      {/* 新增 编辑试剂瓶弹窗 */}
      <AddEditShelfModal />
    </>
  );
};

export default inject("store")(observer(Shelf));
